package com.zhihaihe.file.controller;

import com.alibaba.fastjson.JSON;
import com.zhihaihe.file.dto.user.RegisterDTO;
import com.zhihaihe.file.pojo.UserBean;
import com.zhihaihe.file.service.IUserService;
import com.zhihaihe.file.util.JjwtUtil;
import com.zhihaihe.file.util.R;
import com.zhihaihe.file.util.ResultCodeEnum;
import com.zhihaihe.file.vo.user.UserLoginVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.BeanUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.HashMap;

/**
 *该接口为用户接口，主要做用户登录，注册和校验token
 * @author
 */
@RestController
@Slf4j
@RequestMapping("/user")
public class UserController {
    @Resource
    IUserService userService;

    @PostMapping(value = "/register")
    @ResponseBody
    public R<String> addUser(@Valid @RequestBody RegisterDTO registerDTO) {
        UserBean userBean = new UserBean();
        BeanUtils.copyProperties(registerDTO, userBean);
        userService.registerUser(userBean);
        return R.success("注册成功",null);
    }

    /**
     *  登录接口
     * @param telephone 登录手机号码
     * @param password 密码
     * @return
     */
    @GetMapping("/login")
    @ResponseBody
    public R userLogin(String telephone, String password) {
        UserBean saveUserBean = userService.findUserInfoByTelephone(telephone);

        if (saveUserBean == null) {
            return R.fail("手机号或密码错误！");
        }
        String jwt = "";
        try {
            UserBean sessionUserBean = new UserBean();
            sessionUserBean.setPassword(saveUserBean.getPassword());
            sessionUserBean.setQqPassword(saveUserBean.getQqPassword());
            sessionUserBean.setTelephone(saveUserBean.getTelephone());
            sessionUserBean.setOpenId(saveUserBean.getOpenId());
            jwt = JjwtUtil.createJWT("qiwenshare", "qiwen", JSON.toJSONString(sessionUserBean));
        } catch (Exception e) {
            log.info("登录失败：{[]}", e);
            return R.fail("创建token失败！");
        }

        String passwordHash = new SimpleHash("MD5", password, saveUserBean.getSalt(), 1024).toHex();
        if (passwordHash.equals(saveUserBean.getPassword())) {
            UserLoginVo userLoginVo = new UserLoginVo();
            BeanUtils.copyProperties(saveUserBean, userLoginVo);
            userLoginVo.setToken("Bearer " + jwt);
            return R.success(null,userLoginVo);
        } else {
            return R.fail("手机号或密码错误！");
        }
    }

    @PostMapping("/login")
    public R userLogin(@RequestBody UserBean userBean){
        UserBean saveUserBean = userService.findUserInfoByTelephone(userBean.getTelephone());

        if (saveUserBean == null) {
            return R.fail("手机号或密码错误！");
        }
        String jwt = "";
        try {
            UserBean sessionUserBean = new UserBean();
            sessionUserBean.setPassword(saveUserBean.getPassword());
            sessionUserBean.setQqPassword(saveUserBean.getQqPassword());
            sessionUserBean.setTelephone(saveUserBean.getTelephone());
            sessionUserBean.setOpenId(saveUserBean.getOpenId());
            jwt = JjwtUtil.createJWT("qiwenshare", "qiwen", JSON.toJSONString(sessionUserBean));
        } catch (Exception e) {
            log.info("登录失败：{[]}", e);
            return R.fail("创建token失败！");
        }

        String passwordHash = new SimpleHash("MD5", userBean.getPassword(), saveUserBean.getSalt(), 1024).toHex();
        if (passwordHash.equals(saveUserBean.getPassword())) {
            UserLoginVo userLoginVo = new UserLoginVo();
            BeanUtils.copyProperties(saveUserBean, userLoginVo);
            userLoginVo.setToken("Bearer " + jwt);
            return R.success(null,userLoginVo);
        } else {
            return R.fail("手机号或密码错误！");
        }
    }
    @GetMapping("/checkuserlogininfo")
    @ResponseBody
    public R checkUserLoginInfo(@RequestHeader("token") String token) {
        if ("undefined".equals(token) || !StringUtils.hasText(token)) {
            return R.fail("用户暂未登录");
        }
        UserBean sessionUserBean = userService.getUserBeanByToken(token);
        if (sessionUserBean != null) {
            return R.success(sessionUserBean);
        } else {
            return R.fail("用户暂未登录");
        }
    }
}
